package com.situ.blog.servlet;

import com.situ.blog.pojo.Admin;
import com.situ.blog.pojo.Auth;
import com.situ.blog.pojo.query.AdminQuery;
import com.situ.blog.service.IAdminService;
import com.situ.blog.service.IAuthService;
import com.situ.blog.service.ITypeService;
import com.situ.blog.service.impl.AdminServiceImpl;
import com.situ.blog.service.impl.AuthServiceImpl;
import com.situ.blog.service.impl.TypeServiceImpl;
import com.situ.blog.util.*;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
    private IAdminService adminService = new AdminServiceImpl();
    private IAuthService authService = new AuthServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //System.out.println("AdminServlet.service");
        String method = req.getParameter("method");
        switch (method) {
            case "selectByPage":
                selectByPage(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "toUpdate":
                toUpdate(req, resp);
                break;
            case "updateStatus":
                updateStatus(req, resp);
                break;
            case "selectById":
                selectById(req, resp);
                break;
            case "update":
                update(req, resp);
                break;
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req, resp);
                break;
        }
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        //session.invalidate();
        session.removeAttribute("admin");
        session.removeAttribute("authList");

        Cookie cookie = CookieUtil.getCookie(req, "autoLogin");
        if (cookie != null) {
            //设置Cookie存活时间为0
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
        }

        JSONUtil.toJSON(resp, Result.ok("退出成功"));
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminServlet.login");
        System.out.println("AdminServlet.login");
        System.out.println("AdminServlet.login");
        System.out.println("AdminServlet.login");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            JSONUtil.toJSON(resp, Result.error("验证码错误"));
            return;
        }

        Admin admin = adminService.login(name, password);
        if (admin == null) {
            JSONUtil.toJSON(resp, Result.error("登录失败"));
            return;
        }
        if (admin.getStatus() == 0) {
            JSONUtil.toJSON(resp, Result.error("该用户已经被禁用"));
            return;
        }

        //自动登录
        String autoLogin = req.getParameter("autoLogin");
        if (!ObjectUtils.isEmpty(autoLogin)) {//勾选了自动登录
            Cookie cookie = new Cookie("autoLogin", admin.getName() + "&" + admin.getPassword());
            //设置Cookie的存活时间 一周
            cookie.setMaxAge(60 * 60 * 24 * 7);
            //绑定路径
            cookie.setPath(req.getContextPath());
            //在响应resp添加Cookie，返回给浏览器
            resp.addCookie(cookie);
        }

        //这个用户登录成功这个凭证放到session
        session.setAttribute("admin", admin);
        List<Auth> authList = authService.selectByRole(admin.getRole());
        session.setAttribute("authList", authList);

        // http://localhost:8080/
        // http://localhost:8080/index.jsp
        //resp.sendRedirect("/");
        //req.getRequestDispatcher("/").forward(req, resp);
        JSONUtil.toJSON(resp, Result.ok("登录成功"));

    }

    private void update(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminServlet.update");
        Admin admin = MyBeanUtil.copyToBean(req, Admin.class);
        adminService.update(admin);
        JSONUtil.toJSON(resp, Result.ok("添加成功"));
    }

    private void selectById(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminServlet.selectById");
        String id = req.getParameter("id");
        Admin admin = adminService.selectById(Integer.parseInt(id));
        JSONUtil.toJSON(resp, Result.ok(admin));
    }

    private void updateStatus(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminServlet.updateStatus");
        String id = req.getParameter("id");
        String status = req.getParameter("status");
        adminService.updateStatus(id, Integer.parseInt(status));
        JSONUtil.toJSON(resp, Result.ok("更新成功"));
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("AdminServlet.add");
        Admin admin = MyBeanUtil.copyToBean(req, Admin.class);
        adminService.add(admin);
        JSONUtil.toJSON(resp, Result.ok("添加成功"));
    }

    // /admin?method=selectByPage&page=1&limit=10&name=Java
    private void selectByPage(HttpServletRequest req, HttpServletResponse resp)  {
        System.out.println("AdminServlet.selectByPage");
       /* String page = req.getParameter("page");
        Map<String, String[]> parameterMap = req.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
        try {
            BeanUtils.populate(AdminQuery.class, req.getParameterMap());
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }*/
        AdminQuery adminQuery = MyBeanUtil.copyToBean(req, AdminQuery.class);
        System.out.println(adminQuery);
        PageResult pageResult = adminService.selectByPage(adminQuery);

        JSONUtil.toJSON(resp, pageResult);
    }

    //http://localhost:8080/admin?method=toList
    //http://localhost:8080/page/admin/update
    //http://localhost:8080/page/admin/list
    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("AdminServlet.toUpdate");
        req.getRequestDispatcher("/WEB-INF/admin_update.jsp").forward(req, resp);
    }

    private void toList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("AdminServlet.toList");
        req.getRequestDispatcher("/WEB-INF/admin_list.jsp").forward(req, resp);
    }
}
